package com.taptech.doufu.ui.activity;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.LayoutParams;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.util.ScreenUtil2;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.R;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.bean.personalcenter.PersonalCardInfo;
import com.taptech.doufu.bean.personalcenter.PersonalDynamicBean;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.services.personalcenter.PersonalInfoService;
import com.taptech.doufu.ui.adapter.personalcenter.PersonalDynamicAdapter;
import com.taptech.doufu.ui.view.personalcenter.DynamicListView;
import com.taptech.doufu.ui.view.personalcenter.DynamicListView.HorizontalMoveListener;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.GlideUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.ui.view.PullToRefreshListView.OnLoadAndRefreshListener;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

/**
 * 
 <p>
 * Company: DiaoBao
 * </p>
 * 
 * 
 @author huangzh
 * 
 * 
 @date 2014-3-20
 */

@SuppressLint("NewApi")
@SuppressWarnings("unchecked")
public class PersonalDynamicActivity extends DiaobaoBaseActivity implements
		HttpResponseListener, OnLoadAndRefreshListener, HorizontalMoveListener {

	private DynamicListView contents;
	private View center, top, names, line;
	private ImageView topBg;
	private LinearLayout header;
	private TextView userSignature, userName;
	private static int PersonalTypeNum = 3;
	private int lineWidth = ScreenUtil2.SCREEN_PX_WIDTH / PersonalTypeNum;

	private ImageView userPortarit;
	PersonalDynamicAdapter adapter;
	private int translatDP = ScreenUtil2.dip2px(30);
	private PersonalCardInfo userInfo;
	int centerY, centerHeight, namesY;
	public static Bitmap userHeader;

	List<Object> backupDataSrouce[] = new LinkedList[PersonalTypeNum];
	int windowY = ScreenUtil2.dip2px(208), windwoX = ScreenUtil2.dip2px(9);
	int last[] = new int[PersonalTypeNum], positions[] = new int[PersonalTypeNum], type;
	View dynamiceContents[] = new View[PersonalTypeNum];
	TextView typeTexts[] = new TextView[PersonalTypeNum];

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		if (adapter == null)
			return;
		if (hasFocus && adapter.getDataSource() == null) {
			loadDynamiceData(0, true);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.personal_center_activity_dynamic);
		contents = (DynamicListView) findViewById(R.id.personal_activity_dynamic_list);
		contents.setHorizontalMoveListener(this);
		topBg = (ImageView) findViewById(R.id.personal_activity_dynamic_top_bg);
		// arrow = (ImageView)
		// findViewById(R.id.personal_activity_dynamic_arrow);
		userPortarit = (ImageView) findViewById(R.id.personal_activity_dynamic_user_portrait);

		userName = (TextView) findViewById(R.id.personal_activity_dynamic_user_name);
		userSignature = (TextView) findViewById(R.id.personal_activity_dynamic_user_signature);
		// myDynamicLable = (TextView)
		// findViewById(R.id.personal_activity_dynamic_content_type);
		line = findViewById(R.id.personal_activity_dynamic_line);
		android.widget.RelativeLayout.LayoutParams params = new android.widget.RelativeLayout.LayoutParams(
				lineWidth, ScreenUtil2.dip2px(3));
		params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		line.setLayoutParams(params);
		names = findViewById(R.id.personal_activity_dynamic_user_names);
		dynamiceContents[0] = findViewById(R.id.personal_activity_dynamic_sweep);
		dynamiceContents[1] = findViewById(R.id.personal_activity_dynamic_publish);
		dynamiceContents[2] = findViewById(R.id.personal_activity_dynamic_comment);
//		dynamiceContents[2] = findViewById(R.id.personal_activity_dynamic_collect);

		typeTexts[0] = (TextView) findViewById(R.id.personal_center_activity_dynamic_sweep);
		typeTexts[1] = (TextView) findViewById(R.id.personal_center_activity_dynamic_publish);
		typeTexts[2] = (TextView) findViewById(R.id.personal_center_activity_dynamic_comment);
//		typeTexts[2] = (TextView) findViewById(R.id.personal_center_activity_dynamic_collect);

		center = findViewById(R.id.personal_activity_dynamic_center);
		top = findViewById(R.id.personal_activity_dynamic_top);
		userInfo = (PersonalCardInfo) getIntent().getSerializableExtra(
				Constant.DATA);
//		ImageManager.displayImage(topBg, AccountService.getInstance().getBaseAccount().getUser_head_img(),new NetworkImageResListener() {
//			
//			@Override
//			public void loadComplete(Bitmap bitmap) {
//				userHeader = bitmap;
//				if (userHeader == null) {
//					userHeader = ImageUtil.drawableToBitmap(getResources().getDrawable(
//							R.drawable.default_user_portrait));
//				}
//				topBg.setImageBitmap(ImageBlur.doBlur(userHeader, 50, false));
//				
//			}
//		});
//		if (userHeader == null) {
//			userHeader = ImageUtil.drawableToBitmap(getResources().getDrawable(
//					R.drawable.default_user_portrait));
//		} else {
//			topBg.setImageBitmap(ImageBlur.doBlur(userHeader, 50, false));
//		}
 

		header = new LinearLayout(this);
		header.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				ScreenUtil2.dip2px(202)));
		initVData();
		backupDataSrouce[0] = new LinkedList<Object>();
		backupDataSrouce[1] = new LinkedList<Object>();
		backupDataSrouce[2] = new LinkedList<Object>();
	}

	private void initVData() {
		try {

			String name = AccountService.getInstance().getBaseAccount()
					.getNickname();
			String signature = AccountService.getInstance().getBaseAccount()
					.getUser_signature();

			if (userInfo != null) {
				name = userInfo.getNickname();
				signature = userInfo.getUser_signature();
			}

			this.userName.setText(name);
			this.userSignature.setText(signature);
//			userPortarit.setImageBitmap(userHeader);
			GlideUtil.displayCircleImage(userPortarit, AccountService.getInstance().getBaseAccount().getUser_head_img());

			if (userInfo == null)
				name = "我";
			adapter = new PersonalDynamicAdapter(name, userHeader, this);
			contents.setLoadmoreable(true);
			contents.addHeaderView(header);
			contents.setOnLoadAndRefreshListener(this);
			contents.setAdapter(adapter);
			contents.setOnScrollListener(new OnScrollListener() {
				@Override
				public void onScrollStateChanged(AbsListView view,
						int scrollState) {

					if (contents.isLoadmoreable()) {
						// 判断是否滚动到底部
						boolean scrollEnd = false;
						try {
							if (view.getPositionForView(contents
									.getFootProgress()) == view
									.getLastVisiblePosition())
								scrollEnd = true;
						} catch (Exception e) {
							scrollEnd = false;
						}
						if (scrollEnd && !contents.isFull()) {
							contents.getFootView().setVisibility(View.VISIBLE);
							contents.loadMore();
						}
						if (currentPageIndex==0) {
							MobclickAgent.onEvent(PersonalDynamicActivity.this,"sweep-mine-more");
						}
					}
				}

				@Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					if (centerY == 0) {
						centerY = top.getHeight();
						centerHeight = center.getHeight();
						namesY = (int) names.getY();
					}

					if (firstVisibleItem == 1) {

						if (center.getY() <= centerY) {
							center.setY(centerY + header.getY());
							float alpha = (center.getY() / (float) centerY);
							if (alpha > 0) {
								center.setAlpha(center.getY() / (float) centerY);
							}
						}

						if (center.getY() <= (centerY - centerHeight)
								&& center.getY() >= (centerHeight - centerY)) {

							top.setY(header.getY() + centerHeight);
							topBg.setY(header.getY() + centerHeight);

							if ((center.getY() > (centerY - 2 * centerHeight))
									&& (center.getY() < (centerY - centerHeight))) {
								userSignature.setAlpha(((center.getY() - (centerY - 2 * centerHeight)) / centerHeight));
								int size = 17 + (int) (((center.getY() - (centerY - 2 * centerHeight)) / centerHeight) * 3);
								userName.setTextSize(size);
							}
							if ((center.getY() < (centerY - 2 * centerHeight))) {
								userSignature.setAlpha(0);
								names.setY(namesY + translatDP);
								userName.setTextSize(17);
							}

							if (center.getY() > (centerY - centerHeight)) {
								names.setY(namesY);
								top.setY(0);
								topBg.setY(0);
								userName.setTextSize(20);
							}
						}

						if (center.getY() > centerY) {
							center.setY(centerY);
						}

						if ((center.getY() < (centerY - 2 * centerHeight))
								&& (center.getY() >= 0)) {
							int tansSpace = (int) ((centerY - 2 * centerHeight - center
									.getY()) / (centerY - 2 * centerHeight) * translatDP);
							names.setY(namesY + tansSpace);
						}

						if (center.getY() <= 0) {
							center.setY(0);
							top.setY(centerHeight - centerY);
							topBg.setY(centerHeight - centerY);
						}
					}

					if (firstVisibleItem > 1) {
						names.setY(namesY + translatDP);
						top.setY(centerHeight - centerY);
						topBg.setY(centerHeight - centerY);
						center.setY(0);
						userSignature.setAlpha(0);
						// mCircleName.setTextSize(14);
						userName.setTextSize(17);
						center.setAlpha(0);
					}

					if (firstVisibleItem == 0) {
						names.setY(namesY);
						top.setY(0);
						topBg.setY(0);
						center.setY(centerY);
						userSignature.setAlpha(1);
						userName.setTextSize(20);
						center.setAlpha(1);
					}
				}
			});

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void handleResponse(int handleType, HttpResponseObject response) {
		try {
			switch (handleType) {
			case PersonalInfoService.HANDLE_LOAD_DYNAMIC_STATES:
			case PersonalInfoService.HANDLE_LOAD_OTHER_DYNAMICS:
				if (response.getStatus() == Constant.STATUS_SUCCESS) {
					JSONArray array = ((JSONObject) response.getData())
							.getJSONArray("list");
					TTLog.s("response.getRequestData()==="+response.getRequestData());
					last[(Integer) response.getRequestData()] = ((JSONObject) response
							.getData()).getInt(Constant.LAST);
					List<Object> datas = DiaobaoUtil.jsonArray2BeanList(
							PersonalDynamicBean.class, array);
					adapter.setSuperDatas(datas);
					
					if (array.length() == 0) {
						contents.setFull(true);
					}
				} else {
					UIUtil.toastMessage(this,
							DiaobaoUtil.getErrorTips(response));
				}
				contents.loadMoreComplete();
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	public void back(View view) {
		onBackPressed();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	public void rest(View view) {
		if (center.getY() == 0) {
			names.setY(namesY);
			top.setY(0);
			topBg.setY(0);
			center.setY(centerY);
			userSignature.setAlpha(1);
			userName.setTextSize(20);
			center.setAlpha(1);
			contents.smoothScrollToPosition(0);
		}
	}

	public void loadData() {
		PersonalInfoService.getInstance().loadDynamicStates(
				last[currentPageIndex], currentPageIndex, this);
	}

	@Override
	public void onRefresh() {

	}

	@Override
	public void loadMore() {
		loadData();

	}

	public void showDynamic(View view) {
		if (view.getId() == R.id.personal_activity_dynamic_sweep) {
			MobclickAgent.onEvent(PersonalDynamicActivity.this,"sweep-mine");
			loadDynamiceData(0, last[0] == 0);
		} else if (view.getId() == R.id.personal_activity_dynamic_publish) {
			loadDynamiceData(1, last[1] == 0);
		}  else if (view.getId() == R.id.personal_activity_dynamic_comment) {
			loadDynamiceData(2, last[2] == 0);
		} 
//		else if (view.getId() == R.id.personal_activity_dynamic_collect) {
//			loadDynamiceData(2, last[2] == 0);
//		}
	}

	public void loadDynamiceData(int type, boolean loadable) {
		if (currentPageIndex != type) {
			backupDataSrouce[currentPageIndex].clear();
			if (adapter.getDataSource() != null) {
				backupDataSrouce[currentPageIndex].addAll(adapter.getDataSource());
			}
			positions[currentPageIndex] = contents.getFirstVisiblePosition();
			adapter.clearDateSource();
		}
		typeTexts[currentPageIndex].setTextColor(Color.parseColor("#a5a5a5"));
		currentPageIndex = type;
		typeTexts[currentPageIndex].setTextColor(Color.parseColor("#565656"));
		line.setX(currentPageIndex * lineWidth);
		if (loadable) {
			contents.getFootView().setVisibility(View.VISIBLE);
			contents.getFootMore().setText("彩虹万岁，等等无罪");
			contents.getFootProgress().setVisibility(View.VISIBLE);
			loadData();
		} else {
			adapter.setDataSource(new LinkedList<Object>(
					backupDataSrouce[currentPageIndex]));
			contents.setSelection(positions[currentPageIndex]);
		}
	}

	private int currentPageIndex = 0;

	@Override
	public void leftMove() {
		if (currentPageIndex > 0) {
			loadDynamiceData(currentPageIndex - 1,
					last[currentPageIndex - 1] == 0);
		}

	}

	@Override
	public void rightMove() {
		if (currentPageIndex < 1) {
			loadDynamiceData(currentPageIndex + 1,
					last[currentPageIndex + 1] == 0);
		}
	}

	@Override
	public void move(int space) {
		// line.setX(x)

	}

}
